import { Button, Form, Input, Modal } from "antd"
import { useForm } from "antd/es/form/Form"
import FormItem from "antd/es/form/FormItem"
import { TaskTypeSelect } from "components/taskTpey-select"
import { UserSelect } from "components/UserSelect"
import React,{ useEffect } from "react"
import { useDeleteTask, useEditTask } from "utils/task"
import { useTasksModal, useTasksQueryKey } from "./kanbanutils"


const layout = {
  labelcol: {span:8},
  wrapperCol:{span:16}
}

export const TaskModal = () => {
  const [form] = useForm()
  const {editingTaskId,editingTask,close} = useTasksModal()
  const {mutateAsync:editTask,isLoading:editLoading} = useEditTask(useTasksQueryKey())

  const onCancel = () =>{
    close()
    // 清空表单
    form.resetFields()
  }

  // 修改表单
  const onOk = async () => {
    await editTask({...editingTask,...form.getFieldsValue()})
    close()
  }

  const {mutateAsync} =  useDeleteTask(useTasksQueryKey())
  const startDelete = () =>{
    close()
    Modal.confirm({
      okText:'确定',
      cancelText:'取消',
      title:'确定删除任务吗？',
      onOk(){
       return mutateAsync({id:Number(editingTaskId)})
      }
    })
  }

  useEffect(()=>{
    form.setFieldsValue(editingTask)
  },[form,editingTask])

  return (
    <Modal 
     okText='确认'
     cancelText='取消'
     confirmLoading={editLoading}
     title='编辑任务'
     visible={!!editingTaskId}
     onCancel={onCancel}
     onOk={onOk}
     forceRender={true}
    >
      <Form {...layout} initialValues={editingTask} form={form} style={{marginRight: '0px'}}>
        <Form.Item label='任务名' name='name' rules={[{required:true,message:'请输入任务名'}]}>
          <Input />
        </Form.Item>
        <Form.Item label='经办人' name='processorId'>
          <UserSelect defaultOptionName="经办人"/>
        </Form.Item>
        <Form.Item label='类型' name='typeId' >
          <TaskTypeSelect />
        </Form.Item>
      </Form>
      <div style={{textAlign: 'right'}}>
        <Button onClick={startDelete} style ={{fontSize: '14px'}} size='small'> 删除</Button>
      </div>
    </Modal>
  )
}